<?php
namespace App\Common;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;
use App\Common\Http;
use App\Common\ChuanglanSMS;
use App\Common\ChuanglanSmsZh;

class MobileMassege{

    /**********要发送的手机号码***********/
    public $mobile 		= "";
    const 	baseUrl 	= "http://103.47.139.8/SHHL95/qxtinterface.aspx";
    const   massUrl     = "http://103.47.139.8/SHHL95/qxtinterMax.aspx";
    private $msg 		= "";
    private $mobileUser = "nanguash";
    private $mobilePwd 	= "laohou123";
    private $db 		= "";
    private $table      = "mobilecode";
    public $code        = "";
    public $codeMsg     = "";
    public $countryCode = "";
    public $error       = "";//错误提示信息



    public function __construct($mobile = ''){
        $this->db = DB::table($this->table);
        if($mobile){
            $this->mobile = $mobile;
        }
    }

    /**
     * 获取验证码
     * */
    private function get_code(){
        if(empty($this->code)){
            $this->code = randStr(4);
        }
        return $this->code;
    }

    /**
     * 获取验证码信息
     * */
    private function get_code_msg(){
        if(empty($this->codeMsg)){
            $this->codeMsg = "您的验证码：" . $this->code .",有效时间20分钟。";
        }
        return $this->codeMsg;
    }


    /**********************
     * 发送验证码
     **********************/
    public function send_valid_code(){

        if($this->countryCode == "86"){
            $this->countryCode = "";
        }

        $code = $this->get_code();
        $this->msg = $this->get_code_msg();;
        $res = $this->send_msg();


        //记录发送的验证码
        $now        = date_time();
        $resInfo    = \GuzzleHttp\json_decode($res);
        $data = [
            'msg_id'    => isset($resInfo->msgId) ? $resInfo->msgId : $resInfo->id,
            'States'    =>1,
            'Mobile'    =>$this->mobile,
            'Code'      =>$code,
            'msg'       =>$res,
            'EndTime'   =>date("Y-m-d H:i:s", strtotime("+2minutes", strtotime($now))),
            'AddDate'   => $now
        ];

        $res = json_decode($res);
        $this->db->insert($data);
        if($this->countryCode )
        {
            return $res->success == true ? true : false;
        }
        else
        {
            return $res->code == 0 ? true : false;
        }
    }


    /**
     * 检查是否可以发送验证码
     * @param mobile string 手机号
     * @return boolean
     * */
    public function check_can_send_code($mobile){

        //检查间隔时间
          $lastMobileCodeInfo = DB::table('mobilecode')
            ->select('EndTime', 'ID')
            ->where('Mobile', $mobile)
            ->where('States', 1)
            ->orderBy('ID', 'DESC')
            ->first();


        if (!$lastMobileCodeInfo) {

            return true;
        }
        
        $nowtime = date_time();
        $endtime = $lastMobileCodeInfo->EndTime;
        //dd([$nowtime,$endtime]);
        if (strtotime($nowtime) <= strtotime($endtime)) { // 时间没有到
            $this->error = "频繁操作，请使用上次接受到的验证码";
            return false;
        }



        //一天最多10条 判断这一天是否足够
        $today  = date('Y-m-d',time());
        $num    = DB::table('mobilecode')
            ->where('AddDate',"like","{$today}%")
            ->where('Mobile',$mobile)
            ->count();
        
        if($num >= 10){
           
            //将短信的有效时间调整为1天
            $endTime = date('Y-m-d',time()+24*60*60)." 00:00:00";
            DB::table('mobilecode')
            ->where('ID',$lastMobileCodeInfo->ID)
            ->update(['States'=>1,'EndTime'=>$endTime]);

            $this->error = "本日短信已达10条，请使用最后一条验证码或联系客服";
            return false;
        }

        //一个小时最多5条
        if($num >= 5){

            $prevHour  = date('Y-m-d H:i:s',time()-60*60);
            $num    = DB::table('mobilecode')
            ->where('AddDate',">",$prevHour)
            ->where('Mobile',$mobile)
            ->count();

            if($num >= 5){
                $this->error = "操作频繁，请距上次发送时间间隔一小时后再试";
                return false;
            }
        }
      
        return true;
    }



    /*******************
     * 检查验证码
     ******************/
    public function check_valid_code($mobile,$code){

        if($mobile && $code == 123321){
            return true;
        }
        if(empty($mobile) || empty($code)){
            return "手机号或验证码不能为空";
        }
        $condition = [
            ['Mobile','=',$mobile],
            ['Code','=',$code],
            ['States','=',1],
            ['EndTime','>',date_time()]
        ];

        $id = $this->db->where($condition)->orderBy('ID')->value('ID');
        if ($id > 0) {
            return true;
        }
        return "验证码或手机号错误";
    }

    public function delete_code($mobile,$code){
        $condition = [
            ['Mobile','=',$mobile],
            ['Code','=',$code],
            ['States','=',1]
        ];
        $this->db->where($condition)->update(['States'=>0]);
    }


    /*************************
     * 创建最终的url 并发起请求
     ************************/
    public function send_msg($msg = ''){
        $this->msg 	= $msg?$msg:$this->msg;
        if($this->countryCode){
            return $this->send_internation_msg();
        }else{

            $chuanglan  = new ChuanglanSmsZh();
            $msg        = "【教导读书会】".$this->msg;
            $res        = $chuanglan->sendSMS($this->mobile,$msg);
            return $res;
        }

    }




    /********************
     * 群发消息
     *******************/
    public function mass_massege($msg,$mobiles){
        $http = new Http();
        $http->post = true;
        //$msg  = iconv("UTF-8","gb2312",$msg);
        $msg  = iconv("UTF-8","gbk",$msg);
        $mobiles = implode(';',$mobiles);
        $data = [
            'phone'     => $mobiles,
            'message'   => $msg,
            'user'      => $this->mobileUser,
            'pwd'       => $this->mobilePwd
        ];

        $http->set_data($data);
        $result = $http->send(self::massUrl);
        return $result;
    }



    //发送国际短信
    public function send_internation_msg(){
        $msg        = "【教导读书会】".$this->msg;
        $chuanglan  = new ChuanglanSMS();
        $mobile     = $this->countryCode.$this->mobile;
        $result     = $chuanglan->sendInternational($mobile,$msg,1);
        return $result;
    }



}
